package com.panopset.flywheel;

import static com.panopset.Util.*;

import java.io.StringWriter;

/**
 * <h5>Variable</h5> There is no command associated with a variable, so you drop
 * the <b>&#064</b> directive indicator, and then you specify a variable just as
 * you would in any ant script or unix shell.  The variable must have been defined
 * either in a map provided to the script through Flywheel.Builder.mergeMap, or
 * a Push command.  Please do not define numbers as variable names, as they are
 * used in list processing.
 *
 * <pre>
 * ${variableName}
 *
 * Flywheel pre-defined variables:
 * com.panopset.flywheel.template
 *
 * </pre>
 *
 * @author Karl Dinwiddie
 *
 */
public class CommandVariable extends TemplateCommand implements ReservedWords {


    public static String getShortHTMLText() {
        return "${variableName}";
    }

    public CommandVariable(String source, String innerPiece, Template template) {
        super(source, innerPiece, innerPiece, template);
    }

    @Override
    public String getDescription() {
        return getParams();
    }

    @Override
    public void resolve(StringWriter sw) {
        String p = getParams();
        if (isPopulated(p)) {
            if (p.equals(TEMPLATE)) {
                sw.append(template.getRelativePath());
            } else {
                String str = template.flywheel.get(getParams());
                if (str != null
                        && !template.flywheel.isReplacementsSuppressed) {
                    for (String[] s : template.flywheel.getReplacements()) {
                        str = str.replace(s[0], s[1]);
                    }
                }
                sw.append(str == null ? EMPTY_STRING : str);
            }
        }
    }

}
